import { Console } from "console";
import { createWriteStream, WriteStream } from "fs";
import { ILogger } from "../iLogger.js"
import { conf } from "../../confParse.js"
import { eventHandler, EventCode } from "../../event/eventHandler.js"
import path from "path"

class myLogger implements ILogger {
  constructor(conf: conf) {
    let { logPath, errLogPath } = conf
    if (!logPath || !errLogPath) {
      eventHandler.handle(EventCode.PARSE_CONF_ERROR, "logpath or errLogPath", new Error())
    }
    if (!process.env.id) {
      logPath = path.join(logPath, "./log/log0.log")
      errLogPath = path.join(errLogPath, "./log/err0.log")
    } else {
      logPath = path.join(logPath, `./log/log${process.env.id}.log`)
      errLogPath = path.join(errLogPath, `./log/err${process.env.id}.log`)
    }
    this._outStream = createWriteStream(logPath, { flags: 'a+' })
    this._errStream = createWriteStream(errLogPath, { flags: 'a+' })
    this._logger = new Console(
      this._outStream,
      this._errStream
    );

  }
  private _logger: Console;
  private _outStream: WriteStream
  private _errStream: WriteStream
  public async close(): Promise<void> {
    return new Promise<void>(async (resolve, reject) => {
      await new Promise<void>((res, rej) => {
        this._outStream.close((err) => {
          res()
        })
      })

      this._errStream.close((err) => {
          resolve()
      })
    })

  }
  public log(...msg: string[]) {
    this._logger.log(new Date(), ...msg);
  }
  public err(level: number, ...msg: string[]) {
    this._logger.error(new Date(), level, ...msg)
  }
}
export { myLogger }
